<script lang="ts">
import * as echarts from "echarts";

export default {
  name: "PieChart",
  props: {
    title: {
      type: String,
      required: false,
      validator: (value: string) => {
        return value != null
      }
    },
  },
  data() {
    const option = {
      title: {
        text: this.title ?? "Referer of a Website",
        subtext: "Fake Data",
        left: "center",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        orient: "vertical",
        left: 10,
        bottom: 20,
      },
      grid: {
        left: "3%",
        right: "4%",
        top: "25%",
        bottom: "3%",
        containLabel: true,
      },
      series: [
        {
          name: "Access From",
          type: "pie",
          radius: "50%",
          data: [
            { value: 1048, name: "Search Engine" },
            { value: 735, name: "Direct" },
            { value: 580, name: "Email" },
            { value: 484, name: "Union Ads" },
            { value: 300, name: "Video Ads" },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    return {
      option,
      pieName: "",
      pieValue: "",
      pieColor: "",
    };
  },
  methods: {
    handleClickPie() {
      console.log("--点击饼图--");
    },
  },
  beforeCreate() {
    console.log("--before create--");
  },
  created() {
    console.log("--created--");
  },
  beforeMount() {
    console.log("--beforeMount--");
  },
  mounted() {
    const pieDom = this.$refs.pieRef;
    if (!pieDom) return;

    const pieChart = echarts.init(pieDom as HTMLElement);
    pieChart.setOption(this.option);

    pieChart.on("click", (e) => {
      console.log("--点击饼图--", e);
      this.pieName = e.name;
      this.pieValue = e.value as string;
      this.pieColor = e.color as string;
    });
  },
  beforeUpdate() {
    console.log("--beforeUpdate--");
  },
  updated() {
    console.log("--updated--");
  },
  beforeDestroy() {
    console.log("--beforeDestroy--");
  },
  destroyed() {
    console.log("--destroyed--");
  },
};
</script>

<template>
  <div class="box">
    <div class="chart" ref="pieRef"></div>
    <div class="info" :style="{ background: pieColor }">
      <h3>{{ pieName }}</h3>
      <span>{{ pieValue }}</span>
    </div>
  </div>
</template>

<style scoped>
.box {
  display: flex;
  gap: 20px;
}

.info {
  display: flex;
  flex-direction: column;
  gap: 5;
  color: #333;
}
</style>
